!(function (window, document) {
    'use strict';
    var ddjhoc = {};
    // 我们通常需要 window 和 document


    if (typeof module !== 'undefined' && module.exports) {
        module.exports = ddjhoc
    }
    if (typeof define === 'function') {
        define(function () {
            return ddjhoc
        })
    }

    window.ddjhoc = ddjhoc

})(window, document);
ddjhoc = {
    oBody:  document.querySelector('body'),
    maq: [],
    params: [],         // 达观数据
    ddjParams: [],      // 大当家数据
    plight: [],         // 哪个端的处境
    userAction: {},
    ddjUserAction: {},
    channelId: 1,      // 环境来源 1 H5 2 APP 3 PC
    // memberId: '',
    // openId: '',
    // channelSource: '',
    init: function (fn) {
        var _this = this;

        // Document对象数据
        // if (document) {
        //     _this.params.domain = document.domain || ''; // 获取域名
        //     _this.params.url = document.URL || '';       // 当前Url地址
        //     _this.params.title = document.title || '';
        //     _this.params.referrer = document.referrer || '';  //上一跳路径
        // }

        // Window对象数据
        // if (window && window.screen && window.location) {
        //     _this.params.sh = window.screen.height || 0;    // 获取显示屏信息
        //     _this.params.sw = window.screen.width || 0;
        //     _this.params.host = window.location.host || '';
        //     _this.params.origin = window.location.origin || '';
        //     _this.params.pathname = window.location.pathname || '';
        //     // _this.params.cd = window.screen.colorDepth || 0;
        // }

        // navigator对象数据
        // if (navigator) {
        //     console.log(navigator)
        //     _this.params.lang = navigator.language || '';    // 获取所用语言种类
        //     _this.params.userAgent = navigator.userAgent || '';    // 获取userAgent
        //     _this.params.appVersion = navigator.appVersion || '';    // 浏览器的平台和版本信息。
        // }

        // _this.pushData(_this.maq);
        // console.log(_this.params);

        // _this.setUserId();
        // _this.ddjGetItems();
        // _this.initEvent();

        // environmentInfo.JudgeApp(function () {
        //     // ios
        //     _this.channelId = 2
        // }, function () {
        //     // and
        //     _this.channelId = 2
        // }, function () {
        //     // h5
        //     _this.channelId = 1
        // }, function () {
        //     // pc
        //     _this.channelId = 3
        // });

        if(fn)fn();
    },

    // 放入数据
    pushData: function (maq) {
        var _this = this;
        if (maq) {
            // 获取埋点阶段，传递过来的用户行为
            for (var i=0; i<maq.length; i++) {
                _this.params[i] = {};
                _this.params[i].fields = maq[i][0];
                _this.params[i].cmd = maq[i][1];
            }
        }
    },



    // 初始化事件 点击次数 进入详情
    initEvent: function () {
        var _this = this;
        _this.oBody.addEventListener('touchstart', function (e) {
            var attrJson = {}
            var _tag = e.target;
            var $target;

            if(_tag.nodeName.toLowerCase() == 'a') {
                $target = $(_tag)
            }
            else {
                $target = $(_tag).parents('a');
                // 如果没有找到 a 标签 跳出
                if( $target.length<1 ) return;
            }

            if( $target.attr('href') == undefined ) return;

            attrJson.href = $target.attr('href');
            attrJson.requestid = $target.attr('requestid');
            // if(attrJson.requestid && attrJson.requestid != 'undefined' && attrJson.requestid != 'null') {
            //     attrJson.scenetype = $target.attr('scenetype');
            // }
            attrJson.scenetype = $target.attr('scenetype');
            attrJson.obj = [0];
            _this.ddjSetItems( attrJson );

        });
    },

    // 获取或者设置 userId
    setUserId: function () {
        var _this = this;
        var _getUserInfo = cookie.getCookie( 'ddj-userInfo');
        var _userInfo = '';

        if( _getUserInfo ) {
            // _userInfo = JSON.parse( JSON.parse( _getUserInfo ) );
            _userInfo = JSON.parse( _getUserInfo );
            _this.userAction.memberId = _userInfo.memberId;
            _this.userAction.openId = _userInfo.openId;
            _this.userAction.channelSource = _userInfo.channelSource;
        }


        var _getGuid = cookie.getCookie('ddj_guid');
        if( !_getGuid || _getGuid == undefined) {
            _this.userAction.cid = _this.guid();
            cookie.setCookie('ddj_guid', _this.userAction.cid, 'd3650');
        }
        else {
            _this.userAction.cid = _getGuid;
        }
        // console.log('userAction', _this.userAction)
    },

    // 获取url中的物品编号
    getGoodsNo: function (url) {
        var reg = new RegExp("^YW[a-zA-Z0-9]{12,14}$");
        if(!url) return;
        var aUrl = url.substr(1).split('/');
        for(var i=0; i<aUrl.length; i++) {
            if(aUrl[i].length > 14) {
                if( aUrl[i].indexOf('?') > 0 ) {
                    // alert( aUrl[i].split('?')[0] )
                    return aUrl[i].split('?')[0]
                }
            }
            else {
                if( reg.test(aUrl[i]) ) {
                    return aUrl[i]
                }
            }
        }
    },
    
    // 获取当前时间
    getTime: function () {
        var myDate = new Date();
        var second = parseInt( myDate.getTime()/1000 );
        return second;
    },

    // guid 设置
    guid: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    },

    // 提交单个数据格式设置
    setJson: function ( type, cmd, addArg) {
        var _this = this;
        switch (type) {
            // 加购物车
            case 'cart':
                if( addArg ) {
                    _this.userAction.productId = addArg.pid;
                    _this.userAction.actionNum = addArg.num;
                }
                break;
            // 购买
            case 'buy':
                if( addArg ) {
                    _this.userAction.productId = addArg.pid;
                    _this.userAction.actionNum = addArg.num;
                }
                break;
            // 搜索
            case 'search':
                if( addArg ) {
                    _this.userAction.keyword = addArg;
                }
                break;

            // 评价
            case 'comment':
                if( addArg ) {
                    _this.userAction.productId = addArg;
                }
                break;

            // 收藏和取消
            case 'collect':
                if( addArg ) {
                    _this.userAction.goodsSn = addArg.goodsSn;
                }
                break;
            // 分享
            case 'share':
                if( addArg ) {
                    _this.userAction.goodsSn = addArg.goodsSn;
                }
                break;
            // 点击
            case 'rec_click':
                if( addArg ) {
                    // 进入物品详情
                    if( addArg.href.indexOf('h/goodspay/goodsView') > 0 ) {
                        _this.userAction.goodsSn = _this.getGoodsNo( addArg.href );
                    }
                    else {
                        return
                    }
                }
                break;
            // 预览
            case 'rec_show':
                if( addArg ) {
                    if( addArg.href.indexOf('h/goodspay/goodsView') > 0 ) {
                        _this.userAction.goodsSn = _this.getGoodsNo( addArg.href );
                    }
                    else {
                        return
                    }
                }
                break;
            default:
                break;
        }
        _this.setUserId();
        _this.userAction.actionType = type;
        _this.userAction.timestamp = _this.getTime();
        _this.userAction.recRequestId = '';
        if(addArg.requestid && addArg.requestid != 'undefined' && addArg.requestid != 'null') {
            _this.userAction.recRequestId = addArg.requestid;
        }

        _this.userAction.sceneType = addArg.scenetype;
        // console.log(_this.userAction)
        _this.maq.push( [_this.userAction, cmd] );
        _this.pushData(_this.maq);
        _this.userAction = {};
    },

    setDDJJson: function(addArg, ddjArg) {
        var _this = this;
        // ddj数据统计


        // 设置分类还是首页
        if(ddjArg && ddjArg != 'undefined' && ddjArg != 'null') {
            _this.ddjUserAction.positionId  = ddjArg.positionId;
            // _this.ddjUserAction.positionType  = ddjArg.positionType;
            _this.ddjUserAction.positionFirst  = ddjArg.positionFirst;
            _this.ddjUserAction.positionSecond  = ddjArg.positionSecond;
        }

        // 获取商品goodsid
        if(addArg.goodsid && addArg.goodsid != 'undefined' && addArg.goodsid != 'null') {
            _this.ddjUserAction.goodsid = addArg.goodsid;
            _this.ddjUserAction.itemId = addArg.goodsid;
        }

        // 获取bannerid
        if(addArg.bannerid && addArg.bannerid != 'undefined' && addArg.bannerid != 'null') {
            _this.ddjUserAction.bannerid = addArg.bannerid;
            _this.ddjUserAction.itemType = 2;
            _this.ddjUserAction.itemId = addArg.bannerid;
        }
        else {
            _this.ddjUserAction.itemType = 1;
        }

        if(!_this.ddjUserAction.itemId) return;

        _this.ddjUserAction.channelId = _this.channelId;

        _this.ddjParams.push(_this.ddjUserAction);
        _this.ddjUserAction = {}
    },

    // 循环多个设置数据
    setData: function (data, type, cmd, fn, addArg, ddjArg) {
        var _this = this;
        if(data.length < 1) return;
        _this.maq = [];
        _this.params = [];
        _this.ddjParams = [];
        // 参数是数组处理 （用于多规格购买） show
        if(addArg instanceof Array) {
            for(var i=0; i<data.length; i++) {
                _this.setJson( type, cmd, addArg[i]);
                _this.setDDJJson( addArg[i], ddjArg );
            }
        }
        else {
            for(var j=0; j<data.length; j++) {
                _this.setJson( type, cmd, addArg);
                _this.setDDJJson( addArg, ddjArg );
            }
        }
        if(fn)fn();
    },


    // 设置本地存储
    ddjSetItems: function (params) {
        var sJson = JSON.stringify( params );
        window.localStorage.setItem('ddj_userAct', sJson);
    },

    // 获取本地存储
    ddjGetItems: function () {
        var _this = this;
        var _userAct = window.localStorage.getItem('ddj_userAct');
        // console.log('_userAct', _userAct)
        if ( _userAct ) {
            _userAct = JSON.parse(_userAct);
            _this.setData(_userAct.obj, 'rec_click', 'add', function () {
                console.log('ddjhoc.params.rec_click', _this.params);
                _this.sendData(_this.params, function () {
                    window.localStorage.removeItem('ddj_userAct');
                });
            }, _userAct);
        }
    },

    // 给后台传递达观数据
    sendData: function (jsondata, callBack, error, over) {
        var _Data = [];
        var postData = jsondata;
        if (typeof jsondata != 'string') {
            postData = JSON.stringify(postData);
        }

        $.ajax({
            url: '/m/da/1.0/useraction/collect/data',
            data: {"data": postData},
            type: 'GET',
            dataType: "jsonp",
            //其中success_jsonpCallback为自定义名称，与后台保持一致即可
            jsonpCallback: "success_jsonpCallback",
            //contentType: "application/json; charset=utf-8",
            success: function(data) {
                _Data = eval(data);
                console.log(_Data)
                if (callBack) callBack(_Data);
            },
            error:function(x){
                if(403==x.status) {
                }
                // window.localStorage.removeItem('ddj_userAct');
                if(error)error();
            },
            complete:function (XHR,TS) {
                // window.localStorage.removeItem('ddj_userAct');
                if(over)over();
                XHR = null;
            }
        });
    },

    // 给后台传递大当家数据
    sendDDJData: function (jsondata, callBack, error, over) {
        var _Data = [];
        var postData = jsondata;
        if (typeof jsondata != 'string') {
            postData = JSON.stringify(postData);
        }

        $.ajax({
            url: '/m/da/1.0/useraction/collectshowgoods/data',
            data: {"data": postData},
            type: 'POST',
            dataType: "jsonp",
            //其中success_jsonpCallback为自定义名称，与后台保持一致即可
            jsonpCallback: "success_jsonpCallback",
            //contentType: "application/json; charset=utf-8",
            success: function(data) {
                _Data = eval(data);
                console.log(_Data)
                if (callBack) callBack(_Data);
            },
            error:function(x){
                if(403==x.status) {
                }
                // window.localStorage.removeItem('ddj_userAct');
                if(error)error();
            },
            complete:function (XHR,TS) {
                // window.localStorage.removeItem('ddj_userAct');
                if(over)over();
                XHR = null;
            }
        });
    },
}

var cookie = {
    //s20是代表20秒 h是指小时，如12小时则是：h12 d是天数，30天则：d30
    //写cookies setCookie("ddjAction","hayden",'s20');
    setCookie: function (name,value,time) {
        var _this = this;
        var strsec;
        if (time == undefined) {
            var Days = 30; //默认30天有效期
            strsec = Days*24*60*60*1000;
        }
        else {
            strsec = _this.getsec(time)*1;
        }
        var exp = new Date();
        exp.setTime(exp.getTime() + strsec);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ";path=/";
    },
    getCookie: function (name) {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if( arr=document.cookie.match(reg) ) {
            return unescape(arr[2]);
        }
        else{
            return null;
        }
    },
    delCookie: function () {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
            document.cookie = name + "="+cval+";expires="+exp.toGMTString() + ";path=/";
    },
    // 设置cookie时间
    getsec: function (str) {
        var str1=str.substring(1,str.length)*1;
        var str2=str.substring(0,1);
        if (str2=="s") {
            return str1*1000;
        }
        else if (str2=="h") {
            return str1*60*60*1000;
        }
        else if (str2=="d") {
            return str1*24*60*60*1000;
        }
    }
}

var environmentInfo = {
    // 检测 安卓 ios 隐藏指定对象
    JudgeApp: function (ios, and, h5, pc) {
        var _this = this;
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        // 检测室安卓还是ios
        if( u.search('origin/sfddjapp') > 0 ) {
            if(isIOS) {
                if(ios) ios();
            }
            else {
                if(and) and();
            }
        }

        // 检测ddj-H5
        else if( !_this.IsPC() ) {
            if(h5) h5();
        }
        // PC端
        else {
            if(pc) pc();
        }
    },

    IsPC: function () {
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
            "SymbianOS", "Windows Phone",
            "iPad", "iPod"];
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = false;
                break;
            }
        }
        return flag;
    }
}


